import { useEffect, useRef } from "react";
const { Menu, MenuItem, getCurrentWindow } = window.require("@electron/remote");

const useContextMenu = (menuItemArr, targetSelector, deps) => {
  let clickElement = useRef(null);
  useEffect(() => {
    const menu = new Menu();
    menuItemArr.forEach((c) => {
      menu.append(new MenuItem(c));
    });

    const handleContextMenu = (e) => {
      if (document.querySelector(targetSelector).contains(e.target)) {
        clickElement.current = e.target;
        menu.popup({ window: getCurrentWindow() });
      }
    };
    window.addEventListener("contextmenu", handleContextMenu);
    return () => {
      window.removeEventListener("contextmenu", handleContextMenu);
    };
  }, deps);

  return clickElement;
};

export default useContextMenu;
